define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'deerhome/card/index' + location.search,
                    add_url: 'deerhome/card/add',
                    edit_url: 'deerhome/card/edit',
                    del_url: 'deerhome/card/del',
                    multi_url: 'deerhome/card/multi',
                    import_url: 'deerhome/card/import',
                    dragsort_url: "",
                    table: 'deerhome_card',
                }
            });

            var table = $("#table");
            table.on('post-common-search.bs.table', function (event, table) {
                $(".columns-right").hide();
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                search: false,
                searchFormVisible: true,
                showToggle: false,
                showColumns: false,
                showExport: false,
                fixedColumns: true,
                fixedNumber: 2,
                fixedRightNumber: 1,
                onLoadSuccess:function(){
                    $(".btn-editone").attr('data-shade','0.5').data("area", ['80%','90%']);
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),sortable:true, operate: false}
                        ,{field: 'face_image', title: __('Face_image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'name', title: __('Name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'status', title: __('Status'), addClass:"selectpicker", searchList: {"1":__('Status 1'),"2":__('Status 2')},yes:'1',no:'2', formatter: Table.api.formatter.toggle},
                        {field: 'card_items', title: "包含产品", operate: false,formatter: function (value, row, index) {
                            let a='';
                            value.forEach(function(v,i){
                                a+=`<span style='color:#884ffb'>${v.items_name}/${v.items_gg_name}/${v.items_gg_dw}</span> x ${v.num}<br/>`
                            });
                            return a;
                        }},
                        {field: 'time_area_text', title: '有效期', addClass:"selectpicker", searchList: {'1':'永久','2':'月卡','3':'季卡','4':'年卡'}},
                        {field: 'vip_discount', title: '会员折扣', addClass:"selectpicker", searchList: {'1':'是','2':'否'},yes:'1',no:'2', formatter: Table.api.formatter.toggle},
                        {field: 'item_show', title: '产品页关联', addClass:"selectpicker", searchList: {'1':'是','2':'否'},yes:'1',no:'2', formatter: Table.api.formatter.toggle, operate: false},
                        {field: 'is_home', title: '首页', addClass:"selectpicker", searchList: {'1':'是','2':'否'},yes:'1',no:'2', formatter: Table.api.formatter.toggle},
                        {
                            field: 'anget', title: '参与分销', addClass:"selectpicker",searchList:{'1':'是','2':'否'}, formatter:function(v,r,index){
                                if(v==2){
                                    return `<span class="label label-primary">否</span>`;
                                }
                                return `<span style='color:#884ffb'>上级分佣</span> ${r.anget_lev1}%<br/><span style='color:#884ffb'>上上级分佣</span> ${r.anget_lev2}%`;
                            }
                        },
                        
                        {field: 'price_market', title: __('Price_market'),sortable:true, operate:false},
                        {field: 'price', title: __('Price'),sortable:true, operate:false},
                        {field: 'sale_times', title: '真实销量',sortable:true, operate:false},
                        {field: 'view_times', title: __('View_times'),sortable:true, operate:false},
                        {field: 'weigh', title: __('Weigh'),sortable:true, operate: false},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,sortable:true},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        appendFunc:function(){
            $(".btn-appendItem").on("click", function () {
                let url=$(this).data("urlpop");
                let title=$(this).data("title");
                (parent || self).Fast.api.open(url,title,{
                    shade:0.5,
                    shadeClose:false,
                    callback:function(value){
                      let val=$("textarea[name='row[card_item]']").val();
                      val=JSON.parse(val);
                      let exitIds=[];
                      for(let i=0;i<val.length;i++){
                        exitIds.push(val[i].id);
                      }
                      let repeat=0;
                      for(let i=0;i<value.length;i++){
                        if(exitIds.indexOf(value[i].id)>=0){
                            repeat++;
                            continue;
                        }
                        value[i].num=1;
                        value[i].price_market=value[i].price;
                        val.push(value[i]);
                      }
                      if(repeat>0){
                          Toastr.error("已过滤"+repeat+"个重复产品规格");
                      }
                      val=JSON.stringify(val);
                      $("textarea[name='row[card_item]']").val(val);
                      $(".fieldlist").trigger("fa.event.refreshfieldlist");
                    }
                });
            })
            var sumPrice=function(){
                let val=$("textarea[name='row[card_item]']").val();
                val=JSON.parse(val);
                let price_market=0;
                let price=0;
                for(let i=0;i<val.length;i++){
                    price_market+=parseFloat(val[i].price_market)*parseInt(val[i].num);
                    price+=parseFloat(val[i].price)*parseInt(val[i].num);
                }
                $("input[name='row[price_market]']").val(price_market);
                $("input[name='row[price]']").val(price);
            }
            $(".fieldlist").on("fa.event.refreshfieldlist", function () {
                sumPrice();
            })
            $(".fieldlist").on("click",".btn-remove",function(){
                setTimeout(sumPrice,200);
            })
            $(".fieldlist").on("change",".input_num",function(){
                sumPrice();
            })
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                Controller.appendFunc();
            }
        }
    };
    return Controller;
});
